<script setup lang="ts">
import { computed, ref, onMounted, onBeforeMount } from "vue";
import { filePickerType } from "./type";
import lzcAPIGateway from "./lzcApiGatewayProxy";
import type { filePickerPropsType } from "./type";

const emit = defineEmits(["submit", "close"]);

const props = withDefaults(defineProps<filePickerPropsType>(), {
  type: filePickerType.directory,
  boxId: "",
  multiple: undefined,
  isModal: undefined,
  choiceFileOnly: undefined,
  choiceDirOnly: undefined,
});

const boxId = ref(props.boxId);
// const rootPath=  'https://file.monkeyking.heiyu.space/#/filepicker'
// const targetOrigin ='https://file.monkeyking.heiyu.space'
const rootPath = computed(() => {
  return `https://file.${boxId.value}.heiyu.space/#/filepicker2`;
});
const targetOrigin = computed(() => {
  return `https://file.${boxId.value}.heiyu.space`;
});

const url = computed(() => {
  console.log("props=====>", props);
  const _props = JSON.stringify(props);
  console.log("JSON.stringify(props)====", _props);
  return rootPath.value + `?props=${_props}`;
});
const ifr = ref();

const interval = ref();
window.addEventListener("message", (e) => {
  if (e.data.origin === window.origin) {
    if (e.data.type === "close") {
      emit("close");
    } else if (e.data.type === "submit") {
      emit("submit", e.data.fileList);
    } else if (e.data.type === "init") {
      clearInterval(interval.value);
    }
  }
});
onBeforeMount(async () => {
  if (!boxId.value) {
    //获取boxid
    const gw = lzcAPIGateway;
    const info = await gw.box.QueryInfo({});
    boxId.value = info.boxName;
  }
});
onMounted(() => {
  interval.value = setInterval(() => {
    ifr.value.contentWindow.postMessage(
      {
        type: "init",
      },
      targetOrigin.value
    );
  }, 500);
});
</script>

<template>
  <iframe
    v-if="!!boxId"
    id="iframe"
    ref="ifr"
    style="height: 100%; width: 100%; background: white"
    :src="url"
    frameborder="0"
  ></iframe>
</template>
